<template>
  <div class="app-container">
    <!-- 顶部标题和用户信息 -->
    <div class="header">
      <h1>节日礼品与餐券管理系统</h1>
      <div class="user-info">
        <el-avatar :size="36" :src="userInfo.avatar" />
        <div>
          <div>{{ userInfo.name }}</div>
          <div class="user-email">{{ userInfo.email }}</div>
        </div>
      </div>
    </div>

    <!-- 核心数据卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col
        :xs="24"
        :sm="12"
        :md="8"
        v-for="(stat, index) in statsData"
        :key="index"
      >
        <el-card shadow="hover" class="stat-card">
          <div class="card-title">
            <el-icon :size="20" :color="stat.color">
              <component :is="stat.icon" />
            </el-icon>
            <span>{{ stat.title }}</span>
          </div>
          <div class="card-value">{{ stat.value }}</div>
          <div
            class="card-trend"
            :class="stat.trend === 'up' ? 'trend-up' : 'trend-down'"
          >
            <el-icon>
              <Top v-if="stat.trend === 'up'" />
              <Bottom v-else />
            </el-icon>
            <span>{{ stat.trendText }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 节日商品数据图表 -->
    <el-card shadow="never" class="chart-container">
      <div class="chart-header">
        <div class="chart-title">节日商品销售趋势</div>
        <el-select v-model="chartRange" size="small" style="width: 120px">
          <el-option label="近7天" value="7" />
          <el-option label="近30天" value="30" />
          <el-option label="近90天" value="90" />
        </el-select>
      </div>
      <div ref="chartRef" style="height: 300px"></div>
    </el-card>

    <!-- 待办事项 -->
    <el-row :gutter="20" class="dashboard-section">
      <el-col :span="24">
        <div class="section-title">
          <span>待办事项</span>
          <el-link type="primary" :underline="false">查看全部</el-link>
        </div>
        <el-card shadow="never">
          <el-table :data="todoList" style="width: 100%">
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="{ row }">
                <el-tag :type="getPriorityType(row.priority)" effect="plain">
                  {{ getPriorityText(row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="time" label="截止时间" width="180" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleTodoAction(row)"
                  >处理</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="todoList.length === 0" description="暂无待办事项" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作区域 -->
    <el-row :gutter="20" class="dashboard-section">
      <el-col :span="24">
        <div class="section-title">
          <span>快捷操作</span>
        </div>
        <div class="quick-actions">
          <el-card
            v-for="(action, index) in quickActions"
            :key="index"
            shadow="hover"
            class="action-card"
            @click="navigateTo(action.path)"
          >
            <div class="action-icon">
              <el-icon :size="30" :color="action.color">
                <component :is="action.icon" />
              </el-icon>
            </div>
            <div class="action-title">{{ action.title }}</div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 信息模块 -->
    <el-row :gutter="20" class="dashboard-section">
      <el-col
        :xs="24"
        :sm="12"
        :md="6"
        v-for="(info, index) in infoModules"
        :key="index"
      >
        <el-card shadow="never" class="info-card">
          <div class="info-title">{{ info.title }}</div>
          <div class="info-content">
            <div v-html="info.content"></div>
            <el-button
              v-if="info.button"
              type="primary"
              plain
              size="small"
              @click="handleInfoAction(info.action)"
            >
              {{ info.button }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 页脚 -->
    <div class="footer">
      © 2023 企业礼品与餐券管理系统 | 版本 v{{ systemInfo.version }} |
      {{ systemInfo.department }}
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import * as echarts from "echarts";

import { getPendingDistributorCount } from "@/api/ruoyi/distributor";

import {
  User,
  ShoppingCart,
  Tickets,
  Setting,
  Box,
  Goods,
  Avatar,
  Document,
  Promotion,
  Money,
  DataAnalysis,
  Notebook,
  QuestionFilled,
  Tools,
  Top,
  Bottom,
} from "@element-plus/icons-vue";

// 用户信息
const userInfo = reactive({
  name: "管理员",
  email: "admin@company.com",
  avatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
});

// 核心数据
const statsData = ref([
  {
    title: "员工总数",
    value: "1,248",
    icon: User,
    color: "#409EFF",
    trend: "up",
    trendText: "较上月 +5.2%",
  },
  {
    title: "商品总数",
    value: "86",
    icon: ShoppingCart,
    color: "#E6A23C",
    trend: "up",
    trendText: "较上月 +12.7%",
  },
  {
    title: "本月订单数",
    value: "2,156",
    icon: Tickets,
    color: "#67C23A",
    trend: "down",
    trendText: "较上月 -3.4%",
  },
]);

// 图表相关
const chartRange = ref("30");
const chartRef = ref(null);
let chartInstance = null;

// 待办事项
const todoList = ref([
  {
    id: 1,
    title: "处理中秋月饼订单异常",
    description: "3个订单支付成功但未生成券码",
    priority: "high",
    time: "今天 14:30",
  },
  {
    id: 2,
    title: "审核供应商资质",
    description: "2家新供应商等待资质审核",
    priority: "high",
    time: "今天 16:00",
  },
  {
    id: 3,
    title: "更新节日活动配置",
    description: "中秋节活动即将开始，需更新配置",
    priority: "medium",
    time: "明天 10:00",
  },
  {
    id: 4,
    title: "生成月度销售报表",
    description: "8月份销售数据统计与报表生成",
    priority: "low",
    time: "3天后",
  },
]);

// 快捷操作
const quickActions = ref([
  { title: "员工管理", icon: User, path: "/employee", color: "#409EFF" },
  { title: "系统配置", icon: Setting, path: "/system", color: "#909399" },
  { title: "库存管理", icon: Box, path: "/inventory", color: "#E6A23C" },
  { title: "商品管理", icon: Goods, path: "/products", color: "#67C23A" },
  { title: "客户管理", icon: Avatar, path: "/customers", color: "#F56C6C" },
  { title: "订单管理", icon: Document, path: "/orders", color: "#409EFF" },
  { title: "营销管理", icon: Promotion, path: "/marketing", color: "#E6A23C" },
  { title: "交易管理", icon: Money, path: "/transactions", color: "#67C23A" },
  { title: "数据报表", icon: DataAnalysis, path: "/reports", color: "#F56C6C" },
  { title: "操作日志", icon: Notebook, path: "/logs", color: "#409EFF" },
  { title: "帮助中心", icon: QuestionFilled, path: "/help", color: "#909399" },
  { title: "个人设置", icon: Tools, path: "/settings", color: "#E6A23C" },
]);

// 信息模块
const infoModules = ref([
  {
    title: "操作指南",
    content: `
      <p>系统使用指南和常见问题解答：</p>
      <ul>
        <li>如何添加新员工信息</li>
        <li>商品管理操作流程</li>
        <li>订单处理步骤说明</li>
        <li>报表生成与导出指南</li>
        <li>系统权限配置方法</li>
      </ul>
    `,
    button: "查看完整文档",
    action: "openGuide",
  },
  {
    title: "系统服务",
    content: `
      <p><strong>系统状态：</strong> <el-tag type="success">运行正常</el-tag></p>
      <p><strong>最后维护：</strong> 2023-08-15 02:00-04:00</p>
      <p><strong>下次维护：</strong> 2023-09-10 01:00-03:00</p>
      <p><strong>数据备份：</strong> 每日 03:00 自动备份</p>
      <p><strong>当前版本：</strong> v2.3.1</p>
    `,
    button: "系统设置",
    action: "openSystemSettings",
  },
  {
    title: "联系我们",
    content: `
      <p><strong>技术支持：</strong></p>
      <p>电话：400-123-4567</p>
      <p>邮箱：support@company.com</p>
      <p>工作时间：工作日 9:00-18:00</p>
      <p><strong>反馈与建议：</strong></p>
      <p>欢迎提出宝贵意见帮助我们改进系统</p>
    `,
    button: "提交反馈",
    action: "openFeedback",
  },
  {
    title: "开发信息",
    content: `
      <p><strong>技术栈：</strong></p>
      <p>前端：Vue3 + Element Plus</p>
      <p>后端：Spring Boot + MyBatis</p>
      <p>数据库：MySQL 8.0 + Redis</p>
      <p><strong>开发团队：</strong></p>
      <p>企业数字化解决方案部</p>
      <p>最后更新：2023-08-25</p>
    `,
    button: "更新日志",
    action: "openChangelog",
  },
]);

// 系统信息
const systemInfo = reactive({
  version: "2.3.1",
  department: "企业数字化解决方案部",
});

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);

  const option = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["月饼礼盒", "年货礼包", "自助餐券"],
      bottom: 10,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      top: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["8/1", "8/5", "8/10", "8/15", "8/20", "8/25", "8/30"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "月饼礼盒",
        type: "line",
        smooth: true,
        data: [120, 150, 180, 200, 240, 300, 350],
        lineStyle: {
          width: 3,
        },
      },
      {
        name: "年货礼包",
        type: "line",
        smooth: true,
        data: [80, 100, 120, 150, 180, 200, 220],
        lineStyle: {
          width: 3,
        },
      },
      {
        name: "自助餐券",
        type: "line",
        smooth: true,
        data: [50, 70, 90, 120, 150, 180, 210],
        lineStyle: {
          width: 3,
        },
      },
    ],
  };

  chartInstance.setOption(option);
};

// 获取优先级标签类型
const getPriorityType = (priority) => {
  switch (priority) {
    case "high":
      return "danger";
    case "medium":
      return "warning";
    case "low":
      return "success";
    default:
      return "info";
  }
};

// 获取优先级文本
const getPriorityText = (priority) => {
  switch (priority) {
    case "high":
      return "紧急";
    case "medium":
      return "重要";
    case "low":
      return "一般";
    default:
      return "普通";
  }
};

// 处理待办事项操作
const handleTodoAction = (item) => {
  if (item.id === "distributor-audit") {
    // 跳转到分销员管理页面，筛选待审核记录
    router.push({
      path: "/ruoyi/distributor",
      query: { authStatus: "0" }, // 0表示审核中
    });
  } else {
    console.log("处理待办事项:", item);
  }
};
// const handleTodoAction = (item) => {
//   console.log("处理待办事项:", item);
//   // 实际项目中这里应该是路由跳转或打开弹窗
// };

// 导航到功能页面
const navigateTo = (path) => {
  console.log("导航到:", path);
  // 实际项目中这里应该是路由跳转
  // router.push(path)
};

// 处理信息模块操作
const handleInfoAction = (action) => {
  console.log("执行操作:", action);
  // 根据action执行不同操作
};

// 页面加载时初始化图表
onMounted(() => {
  initChart();
  loadPendingDistributors();
  // 每60秒刷新一次
  const refreshInterval = setInterval(loadPendingDistributors, 60000);

  window.addEventListener("resize", () => {
    if (chartInstance) chartInstance.resize();
  });

  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(refreshInterval);
  });
});
// onMounted(() => {
//   initChart()
//   window.addEventListener('resize', () => {
//     if (chartInstance) chartInstance.resize()
//   })
// })

// ========================================= //

// 待审核分销员数量
const pendingDistributorCount = ref(0);

// 获取待审核分销员数量
const loadPendingDistributors = async () => {
  try {
    const res = await getPendingDistributorCount();
    if (res.code === 200) {
      pendingDistributorCount.value = res.data.count;
      updateTodoList();
    }
  } catch (error) {
    console.error("获取待审核分销员数量失败:", error);
  }
};

// 更新待办事项列表
const updateTodoList = () => {
  // 移除旧的分销员审核事项
  todoList.value = todoList.value.filter(
    (item) => item.id !== "distributor-audit"
  );

  // 添加新的分销员审核事项
  if (pendingDistributorCount.value > 0) {
    todoList.value.unshift({
      id: "distributor-audit",
      title: `审核分销员申请`,
      description: `${pendingDistributorCount.value}个分销员等待审核`,
      priority: "high",
      time: "立即处理",
    });
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.header h1 {
  color: #409eff;
  font-size: 24px;
  font-weight: 600;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-email {
  font-size: 12px;
  color: #909399;
}

/* 核心数据卡片 */
.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  height: 100%;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.card-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

/* 图表区域 */
.chart-container {
  margin-bottom: 24px;
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
}

/* 待办事项 */
.dashboard-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 快捷操作 */
.quick-actions {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 16px;
}

@media (max-width: 1200px) {
  .quick-actions {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 768px) {
  .quick-actions {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 480px) {
  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
}

.action-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-card:hover {
  transform: translateY(-3px);
  background-color: #f0f7ff;
}

.action-icon {
  margin-bottom: 12px;
}

.action-title {
  font-weight: 500;
}

/* 信息模块 */
.info-card {
  height: 100%;
}

.info-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.info-content {
  font-size: 14px;
  line-height: 1.6;
}

.info-content ul {
  padding-left: 20px;
  margin: 10px 0;
}

.info-content li {
  margin-bottom: 8px;
}

/* 页脚 */
.footer {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}
</style>